package com.wxzz.elearing.evaluation.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wxzz.elearing.evaluation.dto.BusinessCategory4EvaluationCriterionDto;
import com.wxzz.elearing.evaluation.dto.BusinessCategoryDto;
import com.wxzz.elearing.evaluation.dto.BusinessCategoryRuleReportDto;
import com.wxzz.elearing.evaluation.dto.EvaluationCriterionDto;
import com.wxzz.elearing.evaluation.entity.*;
import com.wxzz.elearing.evaluation.mapper.*;
import com.wxzz.elearing.evaluation.service.IBusinessCategoryService;
import com.wxzz.elearing.evaluation.service.openfeign.ICurriculumApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IDocentApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IWxLivetelecastApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.evaluation.vo.GeneralStatisticsVo;
import com.wxzz.elearing.evaluation.vo.StarStatisticsVo;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 行业类目/组别管理 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-10
 */
@Service
public class BusinessCategoryServiceImpl extends ServiceImpl<BusinessCategoryMapper, BusinessCategory> implements IBusinessCategoryService {

    @Autowired
    private BusinessCategoryMapper businessCategoryMapper;

    @Override
    public ReturnVO saveBusinessCategory(BusinessCategory businessCategory) {
        if (businessCategory.getId() == null) {
            businessCategoryMapper.insert(businessCategory);
        } else {
            businessCategoryMapper.updateById(businessCategory);
        }
        return new ReturnVO("类目新增成功", businessCategory.getId());
    }

    @Autowired
    private EvaluationCriterionMapper evaluationCriterionMapper;

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategory>>> listBusinessCategory(BusinessCategoryDto businessCategoryDto) {
        PageHelper.startPage(businessCategoryDto.getCurPage(), businessCategoryDto.getMaxPage());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        if (businessCategoryDto.getCommonId() != null) {
            queryWrapper.eq("common_id", businessCategoryDto.getCommonId());
        }
        if (businessCategoryDto.getType() != null) {
            queryWrapper.eq("type", businessCategoryDto.getType());
        }
        if (businessCategoryDto.getBusinessCategoryType() != null) {
            queryWrapper.eq("business_category_type", businessCategoryDto.getBusinessCategoryType());
        }
        if (StringUtils.isNotBlank(businessCategoryDto.getBusinessName())) {
            queryWrapper.like("business_name", businessCategoryDto.getBusinessName() + "%");
        }
        List<BusinessCategory> businessCategories = businessCategoryMapper.selectList(queryWrapper);
        //行业类目
        if (businessCategoryDto.getBusinessCategoryType() == 0) {
            for (BusinessCategory businessCategory : businessCategories) {
                businessCategory.setEvaluationCriterionNum(evaluationCriterionMapper.selectCount(new LambdaQueryWrapper<EvaluationCriterion>()
                        .eq(EvaluationCriterion::getBusinessCategoryId, businessCategory.getId())
                        .eq(EvaluationCriterion::getType, businessCategoryDto.getType())));
            }
        }
        //组别管理
        if (businessCategoryDto.getBusinessCategoryType() == 1) {
            for (BusinessCategory businessCategory : businessCategories) {
                businessCategory.setTopicNum(businessCategoryTopicMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryTopic>()
                        .eq(BusinessCategoryTopic::getBusinessCategoryId, businessCategory.getId())));
            }
        }

        return new ReturnVO("类目列表查询成功", new JgPageVo<>(new PageInfo(businessCategories)));
    }

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategory>>> listBusinessCategory4EvaluationCriterion(BusinessCategory4EvaluationCriterionDto businessCategory4EvaluationCriterionDto) {
        PageHelper.startPage(businessCategory4EvaluationCriterionDto.getCurPage(),businessCategory4EvaluationCriterionDto.getMaxPage());
        QueryWrapper<BusinessCategory> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        //queryWrapper.eq("type",businessCategory4EvaluationCriterionDto.getType());
        if (StringUtils.isNotBlank(businessCategory4EvaluationCriterionDto.getBusinessName())) {
            queryWrapper.like("business_name", businessCategory4EvaluationCriterionDto.getBusinessName() + "%");
        }
        queryWrapper.eq("business_category_type",0);
        List<BusinessCategory> businessCategories = businessCategoryMapper.selectList(queryWrapper);
        for (BusinessCategory businessCategory : businessCategories) {
            businessCategory.setEvaluationCriterionNum(evaluationCriterionMapper.selectCount(new LambdaQueryWrapper<EvaluationCriterion>()
                    .eq(EvaluationCriterion::getBusinessCategoryId, businessCategory.getId())
                    .eq(EvaluationCriterion::getType, businessCategory4EvaluationCriterionDto.getType())));
        }
        return new ReturnVO("类目列表查询成功", new JgPageVo<>(new PageInfo(businessCategories)));
    }

    @Autowired
    private BusinessCategoryTopicMapper businessCategoryTopicMapper;

    @Override
    public ReturnVO<List<BusinessCategory>> wxListBusinessCategory() {
        List<BusinessCategory> businessCategories = businessCategoryMapper.selectList(new LambdaQueryWrapper<BusinessCategory>()
                .eq(BusinessCategory::getBusinessCategoryType, 0));
        return new ReturnVO("行业类目列表查询成功", new JgPageVo<>(new PageInfo(businessCategories)));
    }

    @Override
    public ReturnVO deleteByBusinessCategoryId(Long businessCategoryId) {
        businessCategoryMapper.deleteById(businessCategoryId);
        return new ReturnVO("根据行业类目id删除", businessCategoryId);
    }


    @Override
    public ReturnVO<BusinessCategory> selectCurUserBusinessCategory(Long wxUserId) {
        ReturnVO<String> stringReturnVO = wxUserApiFeign.selectEnterpriseByWxUserId(wxUserId);
        JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
        if (jsonObject.getLong("businessCategoryId") == null) {
            throw new ServiceException("所在企业未绑定行业");
        }
        BusinessCategory businessCategory = businessCategoryMapper.selectById(jsonObject.getLong("businessCategoryId"));
        return new ReturnVO("查询出当前用户对应的测试介绍", businessCategory);
    }

    @Override
    public ReturnVO<String> selectBusinessCategoryById(Long businessCategoryId) {
        BusinessCategory businessCategory = businessCategoryMapper.selectById(businessCategoryId);
        if (businessCategory != null) {
            return new ReturnVO("行业类目名称查询成功", businessCategory.getBusinessName());
        }
        return new ReturnVO("行业类目名称查询成功", null);
    }

    @Autowired
    private BusinessCategoryReportMapper businessCategoryRuleReportMapper;

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryReport>>> listBusinessCategoryReport(BusinessCategoryRuleReportDto businessCategoryRuleReportDto) {
        PageHelper.startPage(businessCategoryRuleReportDto.getCurPage(), businessCategoryRuleReportDto.getMaxPage());
        List<BusinessCategoryReport> businessCategoryRuleReports = businessCategoryRuleReportMapper.selectList(new LambdaQueryWrapper<BusinessCategoryReport>()
                .eq(BusinessCategoryReport::getCommonId, businessCategoryRuleReportDto.getCommonId())
                .eq(BusinessCategoryReport::getType, businessCategoryRuleReportDto.getType()));
        return new ReturnVO("测评报告设置查询成功", new JgPageVo<>(new PageInfo(businessCategoryRuleReports)));
    }

    @Override
    public ReturnVO saveBusinessCategoryReport(BusinessCategoryReport businessCategoryReport) {
        if (businessCategoryReport.getId() == null) {
            businessCategoryRuleReportMapper.insert(businessCategoryReport);
        } else {
            businessCategoryRuleReportMapper.updateById(businessCategoryReport);
        }
        return new ReturnVO("测评报告设置成功", businessCategoryReport.getId());
    }

    @Override
    public ReturnVO saveEvaluationCriterion(EvaluationCriterion evaluationCriterion) {
        if (evaluationCriterion.getId() == null) {
            evaluationCriterionMapper.insert(evaluationCriterion);
        } else {
            evaluationCriterionMapper.updateById(evaluationCriterion);
        }
        return new ReturnVO("测评标准新增或修改成功", evaluationCriterion.getId());
    }

    @Override
    public ReturnVO listEvaluationCriterion(EvaluationCriterionDto evaluationCriterionDto) {
        PageHelper.startPage(evaluationCriterionDto.getCurPage(), evaluationCriterionDto.getMaxPage());
        QueryWrapper<EvaluationCriterion> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("business_category_id",evaluationCriterionDto.getBusinessCategoryId());
        if (evaluationCriterionDto.getType() != null) {
            queryWrapper.eq("type", evaluationCriterionDto.getType());
        }
        if (StringUtils.isNotBlank(evaluationCriterionDto.getEvaluationTitle())) {
            queryWrapper.like("evaluation_title", evaluationCriterionDto.getEvaluationTitle());
        }
        if (evaluationCriterionDto.getStartTime() != null && evaluationCriterionDto.getEndTime() != null) {
            queryWrapper.between("create_time", evaluationCriterionDto.getStartTime(), evaluationCriterionDto.getEndTime());
        }
        List<EvaluationCriterion> evaluationCriteria = evaluationCriterionMapper.selectList(queryWrapper);
        return new ReturnVO("测评标准展示成功", new JgPageVo<>(new PageInfo(evaluationCriteria)));
    }

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Override
    public ReturnVO<JgPageVo<List<EvaluationCriterion>>> wxListEvaluationCriterion(Long wxUserId, EvaluationCriterionDto evaluationCriterionDto) {
        ReturnVO<String> stringReturnVO = wxUserApiFeign.selectEnterpriseByWxUserId(wxUserId);
        JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
        if (jsonObject.getLong("businessCategoryId") == null) {
            throw new ServiceException("所在企业未绑定行业");
        }
        PageHelper.startPage(evaluationCriterionDto.getCurPage(), evaluationCriterionDto.getMaxPage());
        List<EvaluationCriterion> evaluationCriteria = evaluationCriterionMapper.selectList(new LambdaQueryWrapper<EvaluationCriterion>()
                .eq(EvaluationCriterion::getType, evaluationCriterionDto.getType())
                .eq(EvaluationCriterion::getBusinessCategoryId, jsonObject.getLong("businessCategoryId")));
        return new ReturnVO("测评报告展示成功", new JgPageVo<>(new PageInfo(evaluationCriteria)));
    }

    @Override
    public ReturnVO deleteEvaluationCriterion(Long evaluationCriterionId) {
        evaluationCriterionMapper.deleteById(evaluationCriterionId);
        return new ReturnVO("测评报告删除成功", evaluationCriterionId);
    }

    @Autowired
    private ICurriculumApiFeign curriculumApiFeign;

    @Autowired
    private IDocentApiFeign docentApiFeign;

    @Autowired
    private IWxLivetelecastApiFeign wxLivetelecastApiFeign;

    @Autowired
    private BusinessCategoryEvaluationHistoryMapper businessCategoryEvaluationHistoryMapper;

    @Autowired
    private BusinessCategoryRuleHistoryMapper businessCategoryRuleHistoryMapper;

    @Override
    public ReturnVO<GeneralStatisticsVo> selectGeneralStatisticsVo() {
        GeneralStatisticsVo generalStatisticsVo = new GeneralStatisticsVo();
        generalStatisticsVo.setAllLiveNum(wxLivetelecastApiFeign.countByPlatformLivetelecast());
        generalStatisticsVo.setAllActivityNum(wxLivetelecastApiFeign.countByActivity());
        generalStatisticsVo.setAllCourseNum(curriculumApiFeign.countByCourse());
        generalStatisticsVo.setAllPlatformDocentNum(docentApiFeign.countByPlatformDocentNum());
        generalStatisticsVo.setAllEnterpriseDocentNum(docentApiFeign.countByEnterpriseDocentNum());
        Integer evaluationCount = businessCategoryEvaluationHistoryMapper.selectCount(new QueryWrapper<>());
        generalStatisticsVo.setAllEvaluationNum(evaluationCount);
        Integer factoryCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getType, 0));
        generalStatisticsVo.setAllFactoryNum(factoryCount);
        Integer starCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getType, 1));
        generalStatisticsVo.setAllStarNum(starCount);
        generalStatisticsVo.setAllTestNum(evaluationCount + factoryCount + starCount);
        return new ReturnVO<>("综合数据查询成功", generalStatisticsVo);
    }


    @Override
    public ReturnVO<StarStatisticsVo> selectStarStatisticsVo(Long enterpriseId) {
        StarStatisticsVo starStatisticsVo = new StarStatisticsVo();
        Integer oneCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getEnterpriseId, enterpriseId)
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getStartLevel, 1));

        Integer twoCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getEnterpriseId, enterpriseId)
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getStartLevel, 2));

        Integer threeCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getEnterpriseId, enterpriseId)
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getStartLevel, 3));

        Integer fourCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getEnterpriseId, enterpriseId)
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getStartLevel, 4));

        Integer fiveCount = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getEnterpriseId, enterpriseId)
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getStartLevel, 5));

        Integer allJoinNum = oneCount + twoCount + threeCount + fourCount + fiveCount;
        if (!allJoinNum.equals(0)) {
            starStatisticsVo.setOneStar((double) oneCount / allJoinNum * 100);
            starStatisticsVo.setTwoStar((double) twoCount / allJoinNum * 100);
            starStatisticsVo.setThreeStar((double) threeCount / allJoinNum * 100);
            starStatisticsVo.setFourStar((double) fourCount / allJoinNum * 100);
            starStatisticsVo.setFiveStar((double) fiveCount / allJoinNum * 100);
        }
        starStatisticsVo.setAllJoinNum(allJoinNum);
        return new ReturnVO<>("星级认证(概况总览)查询成功", starStatisticsVo);
    }


}
